<?php

class Dao
{
	/**
	 * PDO Database Connection
	 *
	 * @var PDO
	 */
	protected static $database_connection = null;
	protected $ip;
	protected $database;
	protected $username;
	protected $password;
	
	protected $totalRows = 0;
	public static $debug = false;
	
	public function __construct($ip=null,$database=null,$username=null,$password=null)
	{	
		$this->ip = $ip == null ? Config::get("database","server") : $ip;
		$this->database = $database == null ? Config::get("database","database") : $database;
		$this->username = $username == null ? Config::get("database","username") : $username;
		$this->password = $password == null ? Config::get("database","password") : $password;
		$this->connect();
	}
	
	public function connect()
	{
		if(self::$database_connection == null)
		{
			self::$database_connection = new PDO("mysql:host=".$this->ip.";dbname=".$this->database, $this->username, $this->password);
			self::$database_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		}
	}

	public function beginTransaction()
	{			
		$sql = new SqlStatement();
		$sql->setSQL('START TRANSACTION;');
		$this->execute($sql);
	}
	
	public function commitTransaction()
	{
		$sql = new SqlStatement();
		$sql->setSQL('COMMIT;');
		$this->execute($sql);		
	}	
	
	public function rollbackTransaction()
	{
		$sql = new SqlStatement();
		$sql->setSQL('ROLLBACK;');
		$this->execute($sql);			
	}
	
	protected function getHighlightColour($i)
	{
		$array = array('#FF6666','#66FF66','#6666FF','#FF66FF','#FFFF66','#66FFFF','#AAAAAA');
		return $array[$i % count($array)];
	}
	
	protected function highlightBindings($sql)
	{
		$array = str_split($sql);
		$out = array();
		$i = 0;
		foreach($array as $char)
		{
			if($char == '?')
				$out[] = "<font style='font-size: xx-large; BACKGROUND-COLOR: ".$this->getHighlightColour($i++).";'>?</font>";
			else
				$out[] = $char;	
		}
		return implode('',$out);
	}
	
	protected function printDebug($sql,$params,$e=null)
	{
		echo '<table border="1" width="100%">';
		echo '<tr><td colspan=2><pre>'.$this->highlightBindings($sql).'</pre></td></tr>';
				
		$i = 0;
		foreach($params as $param)
		{
			echo "<tr style='background-color: ".$this->getHighlightColour($i++).";'><td>".$i.'</td><td>'.$param.'</td></tr>';
		}
		
		if($e != null)
		{
			echo '<tr><td colspan=2><pre>'.$e->getMessage().'</pre></td></tr>';	
		}
		
		echo '</table>';
	}
	
	public function execute(BaseStatement $statement)
	{
		$sql = $statement->toSQL();
		
		if(self::$debug == true)
		{
			$this->printDebug($sql,$statement->getParams());
		}
			
		$query = self::$database_connection->prepare($sql);
		try {
			$query->execute($statement->getParams());
		} catch(PDOException $e)
		{
			if(self::$debug == true)
			{	
				$this->printDebug($sql,$statement->getParams(),$e);
				die();
			} else {
				throw $e;				
			}
		}
		
		if($statement instanceof Insert)
			$statement->setExecutionResult(self::$database_connection->lastInsertId());
		if($statement instanceof GenericSelect || ($statement instanceof SqlStatement && $statement->getDoResults()))
			$statement->setExecutionResult($query->fetchAll(PDO::FETCH_ASSOC));
		
		if($statement->getCalculateTotalRows())
		{
			$sql = new SqlStatement();
			$sql->setDoResults(true);
			$sql->setSQL('SELECT FOUND_ROWS();');
			$this->execute($sql);
			$results = $sql->getResultSet();
			$this->totalRows = $results[0]['FOUND_ROWS()'];					
		}
	}
	
	/**
	 * getter TotalRows
	 *
	 * @return int
	 */
	public function getTotalRows()
	{
		return $this->totalRows;
	}
}

?>